<!-- 搜索建议 -->
<template>
  <div class="searchSuggest">
    <van-cell v-for="(val, index) in suggestions" :key="index" icon="search">
      <div slot="title" v-html="hightLight(val)" @click="gotoResult(val)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestions } from "@/api/search.js";
import { debounce } from "loadsh";

export default {
  name: "SearchSuggest",
  data() {
    return {
      suggestions: [],
    };
  },
  props: ["searchVal"],
  methods: {
    hightLight(val) {
      return val.replace(
        new RegExp(this.searchVal, "gi"),
        `<span style="color: coral">${this.searchVal}</span>`
      );
    },
    gotoResult(str) {
      this.$emit("search", str);
    },
  },
  watch: {
    searchVal: {
      immediate: true,
      handler: debounce(async function (val) {
        try {
          const { data } = await getSuggestions(val);
          this.suggestions = data.data.options;
        } catch (error) {
          console.log(error);
        }
      }, 300),
    },
  },
};
</script>
<style lang= "less" scoped>
</style>